import React, { useState, useEffect } from 'react';
import { Button, Table, Input, Space, Modal, Form, message, Upload } from 'antd';
import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import type { TableColumnsType } from 'antd';
import { SearchOutlined, PlusOutlined, LoadingOutlined } from '@ant-design/icons';
import styles from './index.less';
import RC from '@/assets/imgs/木材.png';
import { getGoods, addGoods, editGoods, deleteGoods } from '@/api/services';


const WareHouseManagement: React.FC = () => {
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    const [search, setSearch] = useState<string>('');
    const [searchValue, setSearchValue] = useState<string>('');
    const [page, setPage] = useState(1);
    const [total, setTotal] = useState(0);
    const [data, setData] = useState([])
    const [modalOpen, setModalOpen] = useState(false);  //控制新增产品弹窗
    const [editModalOpen, setEditModalOpen] = useState(false);
    const [form] = Form.useForm();
    const [form1] = Form.useForm();
    const [type, setType] = useState<any>('');
    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState<any>();
    const [image, setImage] = useState<any>(); // 添加保存图片文件的状态
    const [goodsId, setGoodsId] = useState('');

    const hasSelected = selectedRowKeys.length > 0;

    const getGoddsList = () => {
        getGoods({
            page: page,
            size: 5,
            name: searchValue ? searchValue : '',
            type: type ? type : ''
        }).then((res: any) => {
            if (res.status == 200) {
                const newData = res.results.map((item: any) => {
                    return { ...item, key: item.goods_id };
                });
                console.log(newData);
                setData(newData);
                setTotal(res.length);
            }

        })
    }

    useEffect(() => {
        getGoddsList();
        console.log(111);
    }, [page, type, searchValue]);

    const handleSearchChange = (e: any) => {
        setSearch(e.target.value);
        if (!e.target.value) {
            setSearchValue(search);
        }
    };
    const onSearch = (e: any) => {
        setSearchValue(search);
    }

    //新增产品
    const addGoodsList = async () => {
        const validate = await form.validateFields();
        const formData = new FormData();
        formData.append("data", JSON.stringify(validate))
        formData.append('image', image);
        addGoods(formData).then((res: any) => {
            if (res.status == 200) {
                message.success('新增成功');
                setModalOpen(false);
                getGoddsList();
            }

        })
    }

    //编辑产品
    const editUserList = async () => {
        const validate = await form1.validateFields();
        console.log('111', validate);
        editGoods({
            goodsId: goodsId,
            num: validate.goods_num
        }).then((res: any) => {
            if (res.status == 200) {
                console.log(res);
                message.success('编辑成功');
                getGoddsList();
                setEditModalOpen(false);
            }

        })
    }

    //删除产品
    const delGoodsList = (id: any) => {
        deleteGoods({ goodsId: id }).then((res: any) => {
            if (res.status == 200) {
                // console.log(res);
                message.success('删除成功');
                getGoddsList();
            }

        })
    }

    const handleChange = (pagination: any, filters: any, sorter: any) => {
        // 更新 type 以根据用户选择的过滤条件进行筛选
        const newType = filters.goods_type ? filters.goods_type[0] : '';
        // console.log(newType);
        setType(newType);
    };

    const columns = [
        {
            title: '产品名称',
            dataIndex: 'goods_name',
        },
        {
            title: '产品类型',
            dataIndex: 'goods_type',
            filters: [
                { text: '原料', value: '原料' },
                { text: '产品', value: '产品' },
            ],
            filterMultiple: false,
            render: (text: any, record: any) => {
                return (
                    record.goods_type == 'material' ? '原料' : '产品'
                )
            }
        },
        {
            title: '产品数量',
            dataIndex: 'goods_num',
        },
        {
            title: '产品图片',
            dataIndex: 'goods_pic',
            render: (text: any, record: any) => {
                return (
                    <img src={record.goods_pic} style={{ width: '100px', height: '100px' }} />
                )
            }
        },
        {
            title: 'Action',
            dataIndex: '',
            key: 'x',
            render: (text: any, record: any) =>
                <Space size="middle">
                    <a
                        onClick={() => {
                            setEditModalOpen(true);
                            setGoodsId(record.goods_id);
                            form1.setFieldsValue(record);
                            console.log('user', record);
                        }}
                    >
                        盘库
                    </a>
                    <a onClick={() => { delGoodsList(record.goods_id) }}>删除</a>
                </Space>
        },
    ];

    //分页器
    const paginationConfig = {
        total: total,
        current: page,
        pageSize: 5,
        onChange: (page: number, pageSize?: number) => {
            setPage(page);
        },
        showTotal: (total: number, range: [number, number]) => `共 ${total} 条数据`,
    }

    const ModalFooter = (
        <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
            <Button
                type="primary"
                style={{ marginRight: 16, borderRadius: 6 }}
                onClick={addGoodsList}
            >
                确定
            </Button>
            <Button
                style={{ marginRight: 16, borderRadius: 6 }}
                onClick={() => { setModalOpen(false) }}
            >
                取消
            </Button>
        </div>
    )

    //编辑客户footer
    const EditModalFooter = (
        <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
            <Button
                type="primary"
                style={{ marginRight: 16, borderRadius: 6 }}
                onClick={editUserList}
            >
                确定
            </Button>
            <Button
                style={{ marginRight: 16, borderRadius: 6 }}
                onClick={() => { setEditModalOpen(false) }}
            >
                取消
            </Button>
        </div>
    )

    const getBase64 = (img: RcFile, callback: (url: string) => void) => {
        const reader = new FileReader();
        reader.addEventListener('load', () => callback(reader.result as string));
        reader.readAsDataURL(img);
    };

    const handleUploadChange: UploadProps['onChange'] = (
        info: UploadChangeParam<UploadFile>,
    ) => {
        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }
        if (info.file.status === 'done') {
            // console.log(info.file);
            getBase64(info.file.originFileObj as RcFile, (url) => {
                setLoading(false);
                setImageUrl(url);
                setImage(info.file.originFileObj as File); // 保存上传的图片文件
            });

        }
    };
    const uploadButton = (
        <div className={styles.uploadButton}>
            {imageUrl ? (
                <img src={imageUrl} alt="avatar" style={{ width: '80%' }} />
            ) : (
                <div>{loading ? <LoadingOutlined onPointerEnterCapture={undefined} onPointerLeaveCapture={undefined} /> : <PlusOutlined onPointerEnterCapture={undefined} onPointerLeaveCapture={undefined} />}</div>
            )}
        </div>
    );

    return (
        <div className={styles.orderContainer}>
            <div className={styles.header}>

                <Input
                    value={search}
                    onChange={handleSearchChange}
                    style={{ width: 240 }}
                    allowClear
                    placeholder="搜索仓库"
                    className={styles.input}
                    suffix={<SearchOutlined onClick={onSearch} onPointerEnterCapture={undefined} onPointerLeaveCapture={undefined} />}
                    onPressEnter={onSearch}
                />
                <Button type="primary" style={{ marginRight: 20 }} onClick={() => { setModalOpen(true) }}>新增产品</Button>
                {/* <Button type="primary" danger>批量删除</Button> */}
            </div>
            <Table columns={columns} dataSource={data}
                onChange={handleChange}
                pagination={paginationConfig}
            />
            {modalOpen &&
                <Modal
                    open={modalOpen}
                    title="新增产品"
                    onCancel={() => { setModalOpen(false) }}
                    footer={ModalFooter}
                >
                    <Form
                        form={form}
                        labelCol={{ span: 4 }}
                        wrapperCol={{ span: 14 }}
                    >
                        <Form.Item label="产品名" name="goods_name">
                            <Input />
                        </Form.Item>
                        <Form.Item label="产品类型" name="goods_type">
                            <Input />
                        </Form.Item>
                        <Form.Item label="产品数量" name="goods_num">
                            <Input />
                        </Form.Item>
                        <Form.Item label="产品图片" name="goods_image">
                            <Upload
                                // name="file"
                                className="avatar-uploader"
                                showUploadList={false}
                                action=""
                                // beforeUpload={beforeUpload}
                                onChange={handleUploadChange}
                            >
                                {uploadButton}
                            </Upload>
                        </Form.Item>
                    </Form>
                </Modal>
            }
            {editModalOpen &&
                <Modal
                    open={editModalOpen}
                    title="盘库"
                    onCancel={() => { setEditModalOpen(false) }}
                    footer={EditModalFooter}
                >
                    <Form form={form1}
                        labelCol={{ span: 6 }}
                        wrapperCol={{ span: 18 }}
                    >
                        <Form.Item label="产品名称" name="goods_name">
                            <Input disabled />
                        </Form.Item>
                        <Form.Item label="产品数量" name="goods_num">
                            <Input />
                        </Form.Item>
                    </Form>
                </Modal>
            }
        </div >
    );
};

export default WareHouseManagement;